/**
 * API 适配器 - 根据配置切换本地模拟或真实 API
 */
import { CentralController } from './CentralController';
import standardApi from '../api/standard';
import { API_MODE } from '../config';
import type {
  RoomState,
  DetailRecord,
  Bill,
  CheckInRecord,
  StatisticsReport,
  ServiceRequest,
} from '../types';
import { ACMode, FanSpeed } from '../types';

/**
 * 统一接口定义
 */
export interface IHvacService {
  // 前台接口
  checkIn(roomId: string, mode: ACMode, guestName?: string, guestPhone?: string, idCard?: string, stayDays?: number, roomType?: string): Promise<{ success: boolean; message: string }>;
  checkOut(roomId: string): Promise<Bill>;
  getDetailRecords(roomId: string): Promise<DetailRecord[]>;
  getBill(roomId: string): Promise<Bill | null>;
  getBillHistory(): Promise<Bill[]>;
  getCheckInRecords(): Promise<CheckInRecord[]>;
  getCheckInRecord(roomId: string): CheckInRecord | null;
  getOccupiedRooms(): string[];

  // 房间接口
  getRoomState(roomId: string): RoomState | null;
  getAllRoomStates(): RoomState[];
  turnOn(roomId: string): Promise<void>;
  turnOff(roomId: string): Promise<void>;
  sendRequest(roomId: string, targetTemp: number, fanSpeed: FanSpeed): Promise<void>;
  setMode(roomId: string, mode: ACMode): Promise<void>;

  // 管理员接口
  getServiceQueue(): any[];
  getWaitingQueue(): any[];
  turnOffAll?(): void | Promise<void>;
  turnOnAll?(): void | Promise<void>;
  clearWaitingQueue?(): void | Promise<void>;
  updateServiceMetrics?(): void;

  // 经理接口
  generateStatistics(startTime: number, endTime: number, roomId?: string): Promise<StatisticsReport>;

  // 系统方法 - 按需刷新
  refreshRoomStates?(): Promise<void>;      // 刷新房间状态
  refreshQueues?(): Promise<void>;          // 刷新队列（管理员用）
  refreshCheckInRecords?(): Promise<void>;  // 刷新入住记录（前台用）
  onStateChange?(callback: () => void): void;
  destroy(): void;

  // 计费服务（仅本地模式）
  billingService?: any;
}

/**
 * 本地模拟模式适配器
 */
class MockAdapter implements IHvacService {
  private controller: CentralController;

  constructor(maxServiceObjects: number, waitTime: number) {
    this.controller = new CentralController(maxServiceObjects, waitTime);
  }

  get billingService() {
    return this.controller.billingService;
  }

  async checkIn(roomId: string, mode: ACMode, guestName?: string, guestPhone?: string, idCard?: string, stayDays?: number, roomType?: string): Promise<{ success: boolean; message: string }> {
    return this.controller.checkIn(roomId, mode, guestName, guestPhone);
  }

  async checkOut(roomId: string): Promise<Bill> {
    const bill = this.controller.checkout(roomId);
    if (!bill) {
      throw new Error(`房间 ${roomId} 没有入住记录或账单`);
    }
    return bill;
  }

  async getDetailRecords(roomId: string): Promise<DetailRecord[]> {
    const state = this.controller.getRoomState(roomId);
    return state ? state.detailRecords : [];
  }

  async getBill(roomId: string): Promise<Bill | null> {
    return this.controller.billingService.getBill(roomId);
  }

  async getBillHistory(): Promise<Bill[]> {
    return this.controller.billingService.getAllBills();
  }

  async getCheckInRecords(): Promise<CheckInRecord[]> {
    return this.controller.getOccupiedRooms().map(roomId => 
      this.controller.getCheckInRecord(roomId)!
    ).filter(record => record !== null);
  }

  getCheckInRecord(roomId: string): CheckInRecord | null {
    return this.controller.getCheckInRecord(roomId);
  }

  getOccupiedRooms(): string[] {
    return this.controller.getOccupiedRooms();
  }

  getRoomState(roomId: string): RoomState | null {
    return this.controller.getRoomState(roomId);
  }

  getAllRoomStates(): RoomState[] {
    return Array.from(this.controller.getAllRoomStates().values());
  }

  async turnOn(roomId: string): Promise<void> {
    this.controller.turnOn(roomId);
    
    // 开机后立即发送服务请求，开始送风
    const room = this.controller.getRoomState(roomId);
    if (room) {
      this.controller.sendRequest(roomId, room.targetTemp, room.fanSpeed);
    }
  }

  async turnOff(roomId: string): Promise<void> {
    this.controller.turnOff(roomId);
  }

  async sendRequest(roomId: string, targetTemp: number, fanSpeed: FanSpeed): Promise<void> {
    this.controller.sendRequest(roomId, targetTemp, fanSpeed);
  }

  async setMode(roomId: string, mode: ACMode): Promise<void> {
    this.controller.setMode(roomId, mode);
  }

  getServiceQueue(): any[] {
    return Array.from(this.controller.getServiceQueue().values());
  }

  getWaitingQueue(): any[] {
    return Array.from(this.controller.getWaitingQueue().values());
  }

  turnOffAll(): void {
    this.controller.turnOffAll();
  }

  turnOnAll(): void {
    this.controller.turnOnAll();
  }

  clearWaitingQueue(): void {
    this.controller.clearWaitingQueue();
  }

  updateServiceMetrics(): void {
    this.controller.updateServiceMetrics();
  }

  async generateStatistics(startTime: number, endTime: number, roomId?: string): Promise<StatisticsReport> {
    // 注意：本地模式不支持按房间筛选，忽略 roomId 参数
    return this.controller.generateStatistics(startTime, endTime);
  }

  onStateChange(callback: () => void): void {
    this.controller.onStateChange(callback);
  }

  destroy(): void {
    this.controller.destroy();
  }
}

/**
 * 真实 API 模式适配器
 */
class ApiAdapter implements IHvacService {
  // 用于临时存储状态（因为前端需要实时访问）
  private roomStatesCache: Map<string, RoomState> = new Map();
  private serviceQueueCache: any[] = [];
  private waitingQueueCache: any[] = [];
  private checkInRecordsCache: Map<string, CheckInRecord> = new Map();
  private stateChangeCallbacks: Set<() => void> = new Set();
  private refreshTimer?: ReturnType<typeof setInterval>;

  constructor() {
    // 初始化时加载基础数据（房间状态和入住记录）
    this.refreshRoomStates();
    this.refreshCheckInRecords();
  }

  // 按需刷新：仅刷新房间状态
  async refreshRoomStates(): Promise<void> {
    try {
      const rooms = await standardApi.rooms.getAllRooms();
      this.roomStatesCache.clear();
      rooms.forEach((room: any) => {
        this.roomStatesCache.set(room.roomId, room);
      });
      this.stateChangeCallbacks.forEach(callback => callback());
    } catch (error) {
      console.error('刷新房间状态失败:', error);
    }
  }

  // 按需刷新：仅刷新队列（管理员页面用）
  async refreshQueues(): Promise<void> {
    try {
      const [serviceQueue, waitingQueue] = await Promise.all([
        standardApi.ac.getServiceQueue(),
        standardApi.ac.getWaitingQueue()
      ]);
      this.serviceQueueCache = serviceQueue;
      this.waitingQueueCache = waitingQueue;
      this.stateChangeCallbacks.forEach(callback => callback());
    } catch (error) {
      console.error('刷新队列失败:', error);
    }
  }

  // 按需刷新：仅刷新入住记录（前台页面用）
  async refreshCheckInRecords(): Promise<void> {
    try {
      // 标准接口暂不支持获取入住记录列表
      // 通过房间状态判断哪些房间已入住
      const rooms = await standardApi.rooms.getAllRooms();
      this.checkInRecordsCache.clear();
      rooms.forEach((room: any) => {
        if (room.isOn) {
          // 创建简单的入住记录
          this.checkInRecordsCache.set(room.roomId, {
            roomId: room.roomId,
            guestName: 'Guest',
            checkInTime: Date.now(),
            mode: room.mode
          });
        }
      });
      this.stateChangeCallbacks.forEach(callback => callback());
    } catch (error) {
      console.error('刷新入住记录失败:', error);
    }
  }

  async checkIn(roomId: string, mode: ACMode, guestName?: string, guestPhone?: string, idCard?: string, stayDays?: number, roomType?: string): Promise<{ success: boolean; message: string }> {
    try {
      await standardApi.checkIn.checkInWithDetails(roomId, {
        guestName: guestName || 'Guest',
        guestPhone: guestPhone || '',
        idCard: idCard || '',
        stayDays: stayDays || 1,
        roomType: roomType || 'STANDARD',
        mode: mode
      });
      return { success: true, message: `房间 ${roomId} 入住办理成功` };
    } catch (error: any) {
      return { success: false, message: error.response?.data?.message || error.message || '入住失败' };
    }
  }

  async checkOut(roomId: string): Promise<Bill> {
    const result = await standardApi.checkOut.checkOut(roomId);
    return result.bill || result;
  }

  async getDetailRecords(roomId: string): Promise<DetailRecord[]> {
    const result = await standardApi.billing.printDetails(roomId);
    return result.details || [];
  }

  async getBill(roomId: string): Promise<Bill | null> {
    try {
      return await standardApi.billing.getBilling(roomId);
    } catch {
      return null;
    }
  }

  async getBillHistory(): Promise<Bill[]> {
    // 标准接口暂不支持获取所有账单，返回空数组
    return [];
  }

  async getCheckInRecords(): Promise<CheckInRecord[]> {
    return Array.from(this.checkInRecordsCache.values());
  }

  getCheckInRecord(roomId: string): CheckInRecord | null {
    return this.checkInRecordsCache.get(roomId) || null;
  }

  getOccupiedRooms(): string[] {
    return Array.from(this.checkInRecordsCache.keys());
  }

  getRoomState(roomId: string): RoomState | null {
    return this.roomStatesCache.get(roomId) || null;
  }

  getAllRoomStates(): RoomState[] {
    return Array.from(this.roomStatesCache.values());
  }

  async turnOn(roomId: string): Promise<void> {
    await standardApi.ac.startAC(roomId);
    // 刷新一次获取最新状态
    await this.refreshRoomStates();
  }

  async turnOff(roomId: string): Promise<void> {
    await standardApi.ac.cancelAC(roomId);
  }

  async sendRequest(roomId: string, targetTemp: number, fanSpeed: FanSpeed): Promise<void> {
    await standardApi.ac.adjustAC(roomId, {
      targetTemp: targetTemp,
      fanSpeed: fanSpeed
    });
  }

  async setMode(roomId: string, mode: ACMode): Promise<void> {
    await standardApi.ac.changeMode(roomId, mode);
  }

  getServiceQueue(): any[] {
    return this.serviceQueueCache;
  }

  getWaitingQueue(): any[] {
    return this.waitingQueueCache;
  }

  async generateStatistics(startTime: number, endTime: number, roomId?: string): Promise<StatisticsReport> {
    // 标准接口暂不支持统计报表，返回空报表
    return {
      startTime,
      endTime,
      totalRooms: 0,
      totalServiceRequests: 0,
      totalCost: 0,
      totalPowerConsumption: 0,
      averageCostPerRoom: 0,
      roomStatistics: [],
      fanSpeedDistribution: {
        low: 0,
        medium: 0,
        high: 0
      }
    };
  }

  // 管理员操作（标准接口暂不支持）
  async turnOffAll(): Promise<void> {
    // 标准接口暂不支持一键关机，逐个关闭
    const rooms = Array.from(this.roomStatesCache.values());
    for (const room of rooms) {
      if (room.isOn) {
        try {
          await this.turnOff(room.roomId);
        } catch (error) {
          console.error(`关闭房间 ${room.roomId} 失败:`, error);
        }
      }
    }
    await Promise.all([
      this.refreshRoomStates(),
      this.refreshQueues()
    ]);
  }

  async turnOnAll(): Promise<void> {
    // 标准接口暂不支持一键开机，逐个开启
    const rooms = Array.from(this.roomStatesCache.values());
    const occupiedRooms = Array.from(this.checkInRecordsCache.keys());
    for (const room of rooms) {
      if (!room.isOn && occupiedRooms.includes(room.roomId)) {
        try {
          await this.turnOn(room.roomId);
        } catch (error) {
          console.error(`开启房间 ${room.roomId} 失败:`, error);
        }
      }
    }
    await Promise.all([
      this.refreshRoomStates(),
      this.refreshQueues()
    ]);
  }

  async clearWaitingQueue(): Promise<void> {
    // 标准接口暂不支持清空等待队列
    console.warn('标准接口暂不支持清空等待队列功能');
    await this.refreshQueues();
  }

  onStateChange(callback: () => void): void {
    this.stateChangeCallbacks.add(callback);
  }

  destroy(): void {
    // 清理所有回调
    this.stateChangeCallbacks.clear();
    // 清空缓存
    this.roomStatesCache.clear();
    this.serviceQueueCache = [];
    this.waitingQueueCache = [];
    this.checkInRecordsCache.clear();
  }
}

/**
 * 创建服务实例（根据配置选择模式）
 */
export function createHvacService(maxServiceObjects: number, waitTime: number): IHvacService {
  if (API_MODE === 'api') {
    console.log('🌐 使用真实后端 API 模式');
    return new ApiAdapter();
  } else {
    console.log('🔧 使用本地模拟模式');
    return new MockAdapter(maxServiceObjects, waitTime);
  }
}

export default createHvacService;

